package com.example.searcher.api;

import com.example.searcher.search.DocResult;
import com.example.searcher.search.DocSearch;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/searcher")
public class DocSearchServelt extends HttpServlet {
    // 这里的 docSearch 应该是属于全局的，而不是对象的
    private static DocSearch docSearch = new DocSearch();
    private ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理请求
        // 处理异常请求
        String query = req.getParameter("query");
        if(query == null || query == ""){
            String msg = "请求参数错误，没有收到查询词！";
            System.out.println(msg);
            resp.sendError(404, msg);
            return;
        }
        System.out.println("query=" + query);
        // 处理正常请求
        // 调用DocSearch中的search方法
        List<DocResult> results =  docSearch.search(query);

        // 包装结果，将结果转化成 JSON 格式的字符串
        // 设置响应结果的类型
        resp.setContentType("application/json;charset=utf-8");
        mapper.writeValue(resp.getWriter(), results);
    }
}
